package shiroDemo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;
/**
 * 验证demo
 * 使用的配置文件为shiro.ini
 * @author xiaou
 * @date 2018年9月20日-下午8:56:31
 */
public class Shiro1 {
	@Test
	public void loginTest() {
		//1.构建securityManager工厂,IniSecurityManagerFactory会从ini的配置文件中初始化securityManager工厂
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		//2.通过工厂获得SecurityManager实例对象
		SecurityManager securityManager = factory.getInstance();
		//3.将securityManager配置到运行环境中
		SecurityUtils.setSecurityManager(securityManager);
		//4.获得subject的实例
		Subject subject = SecurityUtils.getSubject();
		//5.创建用户名，密码身份验证Token
		UsernamePasswordToken token = new UsernamePasswordToken("xiaou", "123");
		try {
			//6.登陆
			//如果登陆失败则抛出异常
			subject.login(token);
		}catch(IncorrectCredentialsException e) {
			System.out.println("用户验证验证失败");
		}
		//7.判断是否登陆成功
		if(subject.isAuthenticated()) {
			System.out.println("用户验证成功");
		}
	}
	/**
	 * 通过数据库验证用户是否正确
	 */
	@Test
	public void loginByDataSourceTest() {
		//1.构建securityManager工厂,IniSecurityManagerFactory会从ini的配置文件中初始化securityManager工厂
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		//2.通过工厂获得SecurityManager实例对象
		SecurityManager securityManager = factory.getInstance();
		//3.将securityManager配置到运行环境中
		SecurityUtils.setSecurityManager(securityManager);
		//4.获得subject的实例
		Subject subject = SecurityUtils.getSubject();
		//5.创建用户名，密码身份验证Token
		UsernamePasswordToken token = new UsernamePasswordToken("aaa", "1111");
		try {
			//6.登陆
			//如果登陆失败则抛出异常
			subject.login(token);
		}catch(IncorrectCredentialsException e) {
			System.out.println("用户验证验证失败");
		}
		//7.判断是否登陆成功
		if(subject.isAuthenticated()) {
			System.out.println("用户验证成功");
		}
	}
}
